/* "The osf_getsysinfo function in arch/alpha/kernel/osf_sys.c in the
   Linux kernel before 2.6.39.4 on the Alpha platform does not properly
   restrict the data size for GSI_GET_HWRPB operations, which allows
   local users to obtain sensitive information from kernel memory via
   a crafted call."

   Fixed in 3d0475119d8722798db5e88f26493f6547a4bb5b on linux-2.6.39.y
   in linux-stable.  */

#include "analyzer-decls.h"
#include "test-uaccess.h"

/* Adapted from include/linux/linkage.h.  */

#define asmlinkage

/* Adapted from include/linux/syscalls.h.  */

#define __SC_DECL1(t1, a1)	t1 a1
#define __SC_DECL2(t2, a2, ...) t2 a2, __SC_DECL1(__VA_ARGS__)
#define __SC_DECL3(t3, a3, ...) t3 a3, __SC_DECL2(__VA_ARGS__)
#define __SC_DECL4(t4, a4, ...) t4 a4, __SC_DECL3(__VA_ARGS__)
#define __SC_DECL5(t5, a5, ...) t5 a5, __SC_DECL4(__VA_ARGS__)
#define __SC_DECL6(t6, a6, ...) t6 a6, __SC_DECL5(__VA_ARGS__)

#define SYSCALL_DEFINEx(x, sname, ...)				\
	__SYSCALL_DEFINEx(x, sname, __VA_ARGS__)

#define SYSCALL_DEFINE(name) asmlinkage long sys_##name
#define __SYSCALL_DEFINEx(x, name, ...)					\
	asmlinkage __attribute__((tainted_args)) \
	long sys##name(__SC_DECL##x(__VA_ARGS__))

#define SYSCALL_DEFINE5(name, ...) SYSCALL_DEFINEx(5, _##name, __VA_ARGS__)

/* Adapted from arch/alpha/include/asm/hwrpb.h.  */

struct hwrpb_struct {
	unsigned long phys_addr;	/* check: physical address of the hwrpb */
	unsigned long id;		/* check: "HWRPB\0\0\0" */
	unsigned long revision;
	unsigned long size;		/* size of hwrpb */
	/* [...snip...] */
};

extern struct hwrpb_struct *hwrpb;

/* Adapted from arch/alpha/kernel/osf_sys.c.  */

SYSCALL_DEFINE5(osf_getsysinfo, unsigned long, op, void __user *, buffer,
		unsigned long, nbytes, int __user *, start, void __user *, arg)
{
	/* [...snip...] */

	__analyzer_dump_state ("taint", nbytes);  /* { dg-warning "tainted" } */

	/* TODO: should have an event explaining why "nbytes" is treated as
	   attacker-controlled.  */

	/* case GSI_GET_HWRPB: */
		if (nbytes < sizeof(*hwrpb))
			return -1;

		__analyzer_dump_state ("taint", nbytes);  /* { dg-warning "has_lb" } */

		if (copy_to_user(buffer, hwrpb, nbytes) != 0) /* { dg-warning "use of attacker-controlled value 'nbytes' as size without upper-bounds checking" } */
			return -2;

		return 1;

	/* [...snip...] */
}

/* With the fix for the sense of the size comparison.  */

SYSCALL_DEFINE5(osf_getsysinfo_fixed, unsigned long, op, void __user *, buffer,
		unsigned long, nbytes, int __user *, start, void __user *, arg)
{
	/* [...snip...] */

	/* case GSI_GET_HWRPB: */
		if (nbytes > sizeof(*hwrpb))
			return -1;
		if (copy_to_user(buffer, hwrpb, nbytes) != 0) /* { dg-bogus "attacker-controlled" } */
			return -2;

		return 1;

	/* [...snip...] */
}
